/* 
 * File:   ServerParallele.c
 * Author: jonas
 *
 * Created on 3 décembre 2013, 16:38
 */
/******* SERVEUR TCP **************/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<string.h>
#include <signal.h> 
#include <pthread.h>

#define PORTS "55555"

void f_thread(int idFils, sockfd, new_fd) {

    //traitement

    pthread_join(idFils - 1);
    close(sockfd);
    for (j = 0; j <= fdmax; j++) { // Envoie données à tous les autre clients j
        if (FD_ISSET(j, &master)) {
            // Sauf serveur et client source données
//            if (j != sockfd && j != i) {
                send(j, buf, nbytes, 0);
//            }
        }
    }
    send(new_fd, "Hello!", 6, 0);
    close(new_fd);
}

int main(int argc, char** argv) {

    int sockfd, new_fd, rv, sin_size, idFils;
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr their_adr;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // use my IP rv = getaddrinfo(NULL, PORTS, &hints, &servinfo); if (rv != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1;}

    // Création socket et attachement
    for (p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("server: socket");
            continue;
        }
        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("server: bind");
            continue;
        }
        break;
    }
    if (p == NULL) {
        fprintf(stderr, "server: failed to bind\n");
        return 2;
    }
    freeaddrinfo(servinfo); // Libère structure
    listen(sockfd, 5);

    while (1) {
        sin_size = sizeof their_addr;
        new_fd = accept(sockfd, &their_addr, &sin_size);
        idFils++;

        pthread_t pthread_id = idFils;
        pthread_create(pthread_id, pthread_attr_default, f_thread, idFils, sockfd, new_fd, buf); //Creation de la thread

    }
}
}

